package com.itheima.reggie.handler;

import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.itheima.reggie.comon.EmployeeGlobalVariable;
import com.itheima.reggie.comon.UserHolder;
import com.itheima.reggie.domain.Employee;
import com.itheima.reggie.domain.User;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class AutoFillHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        //获取对象
        Employee employee = EmployeeGlobalVariable.get();
        //设置默认密码
        String passwordMd5 = SecureUtil.md5("123456");
        this.setFieldValByName("password", passwordMd5, metaObject);
        //自动填充时间
        this.setFieldValByName("createTime", new Date(), metaObject);
        this.setFieldValByName("updateTime", new Date(), metaObject);
        //判断是否为空
        if (employee != null) {
            this.setFieldValByName("createUser", employee.getId(), metaObject);
            this.setFieldValByName("updateUser", employee.getId(), metaObject);
        }
        User user = UserHolder.get();
        if (user != null) {
            this.setFieldValByName("orderTime", new Date(), metaObject);
            this.setFieldValByName("checkoutTime", new Date(), metaObject);
            this.setFieldValByName("createUser", user.getId(), metaObject);
            this.setFieldValByName("updateUser", user.getId(), metaObject);
        }

    }

    @Override
    public void updateFill(MetaObject metaObject) {
        //获取对象
        Employee employee = EmployeeGlobalVariable.get();
        this.setFieldValByName("updateTime", new Date(), metaObject);
        if (employee != null) {
            this.setFieldValByName("updateUser", employee.getId(), metaObject);
        }
        User user = UserHolder.get();
        if (user != null) {
            this.setFieldValByName("updateUser", user.getId(), metaObject);
        }
    }
}
